//
//  ProductPriceTableViewCell.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/26.
//

import UIKit
enum ProductType {
    case normal     //普通
    case time       //限时
    case discount   //折扣
    case vip        //会员
}

class ProductPriceTableViewCell: UITableViewCell {
    var signBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        tempBtn.backgroundColor = UIColor.init(hex: 0xE2CA8A, alpha: 1)
        return tempBtn
    }() // 特价 VIP
    var timeLimitImageView: UIImageView!
    var timeLimitBtn: UIButton!
    var dayBtn: UIButton!//天
    var hourBtn: UIButton!//时
    var minuteBtn: UIButton!//分
    var secondBtn: UIButton!//秒
    var colonLab: UILabel!//冒号
    var colonLab1: UILabel!//冒号
    var colonLab2: UILabel!//冒号
    var activityEndLab: UILabel!//已结束
    var priceLab: UILabel!//售价
    var originalPriceLab: UILabel!//原价
    var timer: Timer!
    var timeCount: NSInteger = 0
    var model: ProductDetailDataModel!
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?){
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = .white
        self.selectionStyle = .none
        self.clipsToBounds = true
        self.initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(){
        
        self.timeLimitImageView = UIImageView(frame: CGRect.zero)
//        self.timeLimitImageView.image = UIImage(named: "icon_flash_special")
        self.timeLimitImageView.image = nil
        self.timeLimitImageView.backgroundColor = .white
        self.contentView.addSubview(self.timeLimitImageView)
        
        self.timeLimitBtn = UIButton(frame: CGRect.zero)
        self.timeLimitBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        self.timeLimitBtn.setTitleColor(.white, for: .normal)
        self.timeLimitBtn.isUserInteractionEnabled = false
        self.timeLimitImageView.addSubview(self.timeLimitBtn)
        
        self.dayBtn = UIButton(frame: CGRect(x: 10, y: 8, width: 18, height: 18))
        self.dayBtn.titleLabel?.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.dayBtn.setTitleColor(.white, for: .normal)
        self.dayBtn.contentHorizontalAlignment = .right
        self.timeLimitImageView.addSubview(self.dayBtn)
        
        self.colonLab = UILabel(frame: CGRect(x: self.dayBtn.right, y: 8, width: 10, height: 18))
        self.colonLab.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.colonLab.textColor = .white
        //self.colonLab.text = ":"
        self.colonLab.textAlignment = .center
        self.timeLimitImageView.addSubview(self.colonLab)
        
        self.hourBtn = UIButton(frame: CGRect(x: self.colonLab.right, y: 8, width: 18, height: 18))
        self.hourBtn.titleLabel?.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.hourBtn.setTitleColor(.white, for: .normal)
        self.timeLimitImageView.addSubview(self.hourBtn)
        
        
        self.colonLab1 = UILabel(frame: CGRect(x: self.hourBtn.right, y: 8, width: 10, height: 18))
        self.colonLab1.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.colonLab1.textColor = .white
        self.colonLab1.textAlignment = .center
        self.colonLab1.text = ":"
        self.timeLimitImageView.addSubview(self.colonLab1)
        
        
        self.minuteBtn = UIButton(frame: CGRect(x: self.colonLab1.right, y: 8, width: 18, height: 18))
        self.minuteBtn.titleLabel?.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.minuteBtn.setTitleColor(.white, for: .normal)
        self.timeLimitImageView.addSubview(self.minuteBtn)
        
        self.colonLab2 = UILabel(frame: CGRect(x: self.minuteBtn.right, y: 8, width: 10, height: 18))
        self.colonLab2.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.colonLab2.textColor = .white
        self.colonLab2.textAlignment = .center
        self.colonLab2.text = ":"
        self.timeLimitImageView.addSubview(self.colonLab2)
        
        self.secondBtn = UIButton(frame: CGRect(x: self.colonLab2.right, y: 8, width: 18, height: 18))
        self.secondBtn.titleLabel?.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
        self.secondBtn.setTitleColor(.white, for: .normal)
        self.timeLimitImageView.addSubview(self.secondBtn)
        
        
        
        self.activityEndLab = UILabel(frame: CGRect.zero)
        self.activityEndLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 12)
        self.activityEndLab.textColor = .white
        self.activityEndLab.textAlignment = .right
        self.activityEndLab.text = MMLocalizedString("finished", comment: "已结束")
        self.timeLimitImageView.addSubview(self.activityEndLab)
        self.activityEndLab.isHidden = true
        
        
        self.priceLab = UILabel(frame: .zero)
        self.priceLab.textColor = .white
        self.priceLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 20)
        self.priceLab.textAlignment = .left
        self.timeLimitImageView.addSubview(self.priceLab)
        //self.timeLimitImageView.addSubview(signBtn)
        
        self.originalPriceLab = UILabel(frame: .zero)
        self.originalPriceLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 11)
        self.originalPriceLab.textColor = .white
        self.originalPriceLab.textAlignment = .left
        self.timeLimitImageView.addSubview(self.originalPriceLab)
        
        self.addLayout()
        
    }
    
    
    func addLayout(){
        
        self.timeLimitImageView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(70)
            make.bottom.equalTo(0)
        }
        
        
        self.timeLimitBtn.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.left.equalTo(14)
            make.height.equalTo(20)
        }
        
        
        self.activityEndLab.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.right.equalTo(-14)
            make.width.equalTo(150)
            make.height.equalTo(20)
        }
        
        self.secondBtn.snp.makeConstraints { (make) in
            make.top.equalTo(6)
            make.left.equalTo(self.colonLab2.snp.right).offset(0)
            make.right.equalTo(-11)
            make.width.equalTo(20)
            make.height.equalTo(30)
        }
        
        
        self.colonLab2.snp.makeConstraints { (make) in
            make.top.equalTo(6)
            make.right.equalTo(self.secondBtn.snp.left).offset(0)
            make.width.equalTo(3)
            make.height.equalTo(30)
        }
        
        
        self.minuteBtn.snp.makeConstraints { (make) in
            make.top.equalTo(6)
            make.right.equalTo(self.colonLab2.snp.left).offset(0)
            make.width.equalTo(20)
            make.height.equalTo(30)
        }
        
        
        
        self.colonLab1.snp.makeConstraints { (make) in
            make.top.equalTo(6)
            make.right.equalTo(self.minuteBtn.snp.left).offset(0)
            make.width.equalTo(3)
            make.height.equalTo(30)
        }
        
        
        
        self.hourBtn.snp.makeConstraints { (make) in
            make.top.equalTo(6)
            make.right.equalTo(self.colonLab1.snp.left).offset(0)
            make.width.equalTo(20)
            make.height.equalTo(30)
        }
        
        
        self.colonLab.snp.makeConstraints { (make) in
            make.top.equalTo(6)
            make.right.equalTo(self.hourBtn.snp.left).offset(0)
            make.width.equalTo(3)
            make.height.equalTo(30)
        }
        
        
        self.dayBtn.snp.makeConstraints { (make) in
            make.top.equalTo(6)
            make.right.equalTo(self.colonLab.snp.left).offset(0)
            make.height.equalTo(30)
            make.width.greaterThanOrEqualTo(30)
        }
        
        self.priceLab.snp.makeConstraints { make in
            make.top.equalTo(self.timeLimitBtn.snp.bottom)
            make.left.equalTo(14)
            make.height.equalTo(28)
        }
        
        self.originalPriceLab.snp.makeConstraints { make in
            make.top.equalTo(self.timeLimitBtn.snp.bottom)
            make.left.equalTo(self.priceLab.snp.right).offset(4)
            make.height.equalTo(28)
        }
        
    }
    
    
    
    //setModel
    func dataModel(model: ProductDetailDataModel){
        self.model = model
        if self.timer != nil {
            self.timeCount = 0
            self.timer.invalidate()
            self.timer = nil
        }
        
        //price、discountPrice、memberPrice哪个价格最低显示哪个，如果是会员价最低标签就是vip，如果折扣价最低标签就是特价
        let lowestPrice = min(model.discountPrice ?? CGFLOAT_MAX, model.memberPrice ?? CGFLOAT_MAX, model.price ?? CGFLOAT_MAX)
        
        self.priceLab.text = XTManageCenter.currentSign() + XTManageCenter.showPriceInComma(source: lowestPrice.cleanZero)
        self.dayBtn.isHidden = true
        self.colonLab.isHidden = true
        self.hourBtn.isHidden = true
        self.colonLab1.isHidden = true
        self.secondBtn.isHidden = true
        self.colonLab2.isHidden = true
        self.minuteBtn.isHidden = true
        
        self.timeLimitBtn.isHidden = false
        
        let type = self.getProductType()
        switch type {
            case .time:
                self.timeUpdata()
                self.timeLimitBtn.setTitle(MMLocalizedString("flash_sale", comment: "限时抢购"), for: .normal)
                if self.timeCount == 0{//活动结束
                    self.timeLimitImageView.image = UIImage(named: "icon_activity_end")
                    self.activityEndLab.isHidden = false
                }else{
                    self.timeLimitImageView.image = UIImage(named: "icon_flash_special")
                }
                
                self.setTimeContent(timeCount: self.timeCount)
                self.timer = Timer.scheduledTimer(timeInterval: 1, target: self , selector: #selector(timeAction), userInfo: nil, repeats: true)
                RunLoop.current.add(self.timer, forMode: RunLoopMode.commonModes)
            case .discount:
                self.timeLimitBtn.setTitle(MMLocalizedString("special", comment: "特价"), for: .normal)
                self.timeLimitImageView.image = UIImage(named: "icon_vip")
                self.timeLimitBtn.setTitleColor(UIColor(hex: 0xE2CA8A), for: .normal)
                self.priceLab.textColor = UIColor(hex: 0xE2CA8A)
                self.originalPriceLab.textColor = UIColor(hex: 0xE2CA8A)
            case .vip:
                self.timeLimitBtn.setTitle("", for: .normal)
                self.timeLimitBtn.setImage(UIImage(named: "icon_vip_imag"), for: .normal)
                self.timeLimitImageView.image = UIImage(named: "icon_vip")
                self.priceLab.textColor = UIColor(hex: 0xE2CA8A)
                self.originalPriceLab.textColor = UIColor(hex: 0xE2CA8A)
            default:
                self.timeLimitBtn.isHidden = true
                self.timeLimitImageView.image = nil
                self.timeLimitImageView.backgroundColor = .white
                self.priceLab.textColor = Theme.mainColor
                self.originalPriceLab.textColor = UIColor(hex: 0xAFBED7)
        }
        
        if type == .normal {
            //不展示划线价
            self.originalPriceLab.attributedText = nil
            self.originalPriceLab.text = ""
        }else{
            //展示划线价 划线价取price
            self.originalPriceLab.attributedText = nil
            self.originalPriceLab.text = ""
            var tempPrice = model.price ?? 0
            if type == .time {
                //【限时抢购】的划线价取originalPrice字段
                tempPrice = model.originalPrice ?? 0
            }
            let originalPriceStr = XTManageCenter.showPriceInComma(source: tempPrice.cleanZero)
            let originalPrice = NSMutableAttributedString.init(string: String(format: "%@%@", XTManageCenter.currentSign(),originalPriceStr))
            originalPrice.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSNumber.init(value: 1), range:  NSRange(location: 0, length: originalPrice.length))
            self.originalPriceLab.attributedText = originalPrice
        }
        self.updateConstraints()
    }
    
    ///获取商品类型
    ///price、discountPrice、memberPrice哪个价格最低显示哪个，如果是会员价最低标签就是vip，如果折扣价最低标签就是特价
    private func getProductType() -> ProductType {
        guard self.model != nil else {
            return .normal
        }
        if self.model.isLimitedTime ?? 0 == 1 {
            return .time
        }
        let price = self.model.price ?? 0
        let discountPrice = self.model.discountPrice ?? 0
        let memberPrice = self.model.memberPrice ?? 0
        if discountPrice == 0 && memberPrice == 0 {
            //普通商品
            return .normal
        } else if discountPrice > 0 && memberPrice > 0 {
            if discountPrice <= memberPrice {
                //特价
                return .discount
            }else{
                //会员
                return .vip
            }
        } else if discountPrice > 0 && discountPrice < price{
            return .discount
        }else if memberPrice > 0 && memberPrice < price {
            return .vip
        }
        return .normal
    }
    
    func timeUpdata(){
        self.dayBtn.isHidden = false
        self.colonLab.isHidden = false
        self.secondBtn.isHidden = false
        self.colonLab2.isHidden = false
        self.secondBtn.snp.updateConstraints { make in
            make.width.equalTo(20)
        }
        self.colonLab2.snp.updateConstraints { make in
            make.width.equalTo(3)
        }
        
        self.minuteBtn.isHidden = false
        self.colonLab1.isHidden = false
        self.minuteBtn.snp.updateConstraints { make in
            make.width.equalTo(20)
        }
        self.colonLab1.snp.updateConstraints { make in
            make.width.equalTo(3)
        }
        
        
        self.hourBtn.isHidden = false
        self.colonLab.isHidden = false
        self.hourBtn.snp.updateConstraints { make in
            make.width.equalTo(20)
        }
        self.colonLab.snp.updateConstraints { make in
            make.width.equalTo(3)
        }
        
        
        self.timeCount = (self.model?.activityTime ?? 0)/1000
        let tempStr = XTManageCenter.calculateDateTimeFromNowBySecond(ms: self.timeCount)
        let tempArray = tempStr.components(separatedBy: ":")//没有天的时候隐藏其中秒的格子
        
        if tempArray.count == 4 {
            self.secondBtn.isHidden = false
            self.colonLab2.isHidden = false
        }else if tempArray.count == 3{
            self.secondBtn.isHidden = true
            self.colonLab2.isHidden = true
            self.secondBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab2.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
        }else if tempArray.count == 2{
            self.secondBtn.isHidden = true
            self.colonLab2.isHidden = true
            self.secondBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab2.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            
            self.minuteBtn.isHidden = true
            self.colonLab1.isHidden = true
            self.minuteBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab1.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
        }else if tempArray.count == 1{
            self.secondBtn.isHidden = true
            self.colonLab2.isHidden = true
            self.secondBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab2.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            
            self.minuteBtn.isHidden = true
            self.colonLab1.isHidden = true
            self.minuteBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.colonLab1.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            
            self.hourBtn.isHidden = true
            self.colonLab.isHidden = true
            self.hourBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            self.hourBtn.snp.updateConstraints { make in
                make.width.equalTo(0)
            }
            
        }else{
            self.secondBtn.isHidden = true
            self.colonLab2.isHidden = true
        }
        
        
    }
    
    //防止第一次服用变一下
    func setTimeContent(timeCount: NSInteger) {
        let tempStr = XTManageCenter.calculateDateTimeFromNowBySecond(ms: self.timeCount)
        let tempArray = tempStr.components(separatedBy: ":")//没有天的时候隐藏其中秒的格子
        if tempArray.count > 0 {
            self.dayBtn.setTitle(String(format: "%@", tempArray[0]), for: .normal)
        }
        if tempArray.count > 1 {
            self.hourBtn.setTitle(String(format: "%@", tempArray[1]), for: .normal)
        }
        if tempArray.count > 2 {
            self.minuteBtn.setTitle(String(format: "%@", tempArray[2]), for: .normal)
        }
        
        if tempArray.count > 3 {
            self.secondBtn.setTitle(String(format: "%@", tempArray[3]), for: .normal)
        }
    }
    
    
    
    
    @objc func timeAction(){
        if self.timeCount > 0 {
            self.timeCount = self.timeCount - 1
            let tempStr = XTManageCenter.calculateDateTimeFromNowBySecond(ms: self.timeCount)
            let tempArray = tempStr.components(separatedBy: ":")
            if tempArray.count > 0 {
                self.dayBtn.setTitle(String(format: "%@", tempArray[0]), for: .normal)
            }
            if tempArray.count > 1 {
                self.hourBtn.setTitle(String(format: "%@", tempArray[1]), for: .normal)
            }
            if tempArray.count > 2 {
                self.minuteBtn.setTitle(String(format: "%@", tempArray[2]), for: .normal)
            }
            
            if tempArray.count > 3 {
                self.secondBtn.setTitle(String(format: "%@", tempArray[3]), for: .normal)
            }
            
        }else{
            //说明今天的秒杀已过
            self.timeCount = 0
            if self.timer != nil {
                self.timer.invalidate()
                self.timer = nil
            }
            
            self.dayBtn.setTitle("--", for: .normal)
            self.hourBtn.setTitle("--", for: .normal)
            self.minuteBtn.setTitle("--", for: .normal)
            self.secondBtn.setTitle("--", for: .normal)
            //活动结束
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "mainRefreash"), object: nil)
        }
    }
    
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
}

